package com.icinfo.cloud.provider.common.page;


import com.icinfo.framework.mybatis.pagehelper.Page;
import com.icinfo.framework.mybatis.pagehelper.datatables.PageRequest;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述：分页结果对象
 *
 * @author xiangyuyu
 * @date 2021-12-30 19:55
 */
@Data
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
public class PageResponse<T> implements Serializable {
    private static final long serialVersionUID = -5584061128249495676L;
    /**
     * 请求次数计数器
     */
    private int draw;
    /**
     * 总记录数
     */
    private long recordsTotal;
    /**
     * 过滤后的记录数
     */
    private long recordsFiltered;
    /**
     * 返回的分页数据对象
     */
    private List<T> data = new ArrayList<>();
    /**
     * 错误提示信息
     */
    private String error;

    /**
     * 构建DataTables分页结果
     *
     * @param data
     */
    public PageResponse(List<T> data) {
        if (data instanceof Page) {
            Page<T> page = (Page<T>) data;
            this.recordsTotal = page.getTotal();
            this.recordsFiltered = page.getTotal();
            this.data = data;
        }
    }

    /**
     * 构建DataTables分页结果
     *
     * @param data  分页数据
     * @param total 总记录数
     */
    public PageResponse(List<T> data, long total) {
        this(data, total, null);
    }

    /**
     * 构建DataTables分页结果
     *
     * @param data    分页数据
     * @param total   总记录数
     * @param request 分页请求对象
     */
    public PageResponse(List<T> data, long total, PageRequest request) {
        this.recordsTotal = total;
        this.recordsFiltered = total;
        if (data != null) {
            this.data = data;
        }
        if (request != null) {
            this.draw = request.getDraw();
        }
    }

}